import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/album_utils.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/widgets/widget_picker_style.dart';
import 'package:get/get.dart';

class MineEditUserLogic extends GetxController {
  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  showAgePicker() async {
    // 生成年龄范围：16-80
    final ages = List.generate(80 - 16 + 1, (index) => (index + 16).toString());
    int initIndex = AppUserManager().user.value?.age ?? 0;
    Pickers.showSinglePicker(
      Get.context!,
      data: ages,
      selectData: initIndex.toString(),
      pickerStyle: WidgetPickerStyle.createPickerStyle(),
      onConfirm: (var selected, int data) async {
        await AppUserManager()
            .saveUserInfo(age: (data + 16).toString(), showLoading: true);
      },
    );
  }

  void pickAndUploadAvatar() async {
    final asset = await AlbumUtils.pickSingleImage();
    if (asset == null) return;

    final file = await asset.file;
    if (file == null) return;

    final bytes = await file.readAsBytes();
    final fileName =
        "phone_${DateTime.now().millisecondsSinceEpoch}.${file.path.split('.').last}";

    // LoadingUtils.showLoading();

    final response = await HttpManager().upload(
        fileData: bytes,
        fileName: fileName,
        requestId: AppUserManager().uid.toString(),
        onSendProgress: (index, total) {
          clog('message    $index   $total');
        });

    // LoadingUtils.dismiss();

    if (response.isSuccess && response.data != null) {
      // idCardFrontPath.value = response.data['url'];
      await AppUserManager()
          .saveUserInfo(avatar: response.data['url'], showLoading: true);
      // idCardFrontUploaded.value = true;
      // registerModelRx.update((val) {
      //   val?.idCardFront = idCardFrontPath.value;
      // });
      // checkButtonState();
    } else {
      LoadingUtils.showToast(LocaleKeys.upload_failed.tr);
    }
    // } catch (e) {
    //   LoadingUtils.dismiss();
    //   LoadingUtils.showToast(LocaleKeys.upload_failed.tr);
    // }
  }
}
